package com.feihong.txgw.ui.activity.product;

import android.content.DialogInterface;
import android.content.Intent;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.LogUtils;
import com.feihong.txgw.R;
import com.feihong.txgw.greendao.gen.ShopCarGoodsModelDao;
import com.feihong.txgw.http.HttpTools;
import com.feihong.txgw.http.RefreshToken;
import com.feihong.txgw.inter.contract.product.IProDetailContract;
import com.feihong.txgw.json.goodsCart.GoodsCartParser;
import com.feihong.txgw.message.LoginMessage;
import com.feihong.txgw.message.UpdateCartMessage;
import com.feihong.txgw.model.greendao.ShopCarGoodsModel;
import com.feihong.txgw.tx_precenter.ProDetailMainPrecenter;
import com.feihong.txgw.ui.activity.order.ToCreateOrderActivity;
import com.feihong.txgw.ui.activity.product.webviewinterface.ProductInfoWebViewInterface;
import com.feihong.txgw.ui.activity.user.MyShopCartActivity;
import com.feihong.txgw.ui.mvp.BaseMVPCompateActivity;
import com.feihong.txgw.ui.mvp.precenter.AbBasePrecenter;
import com.feihong.txgw.utils.ToastUtils;
import com.feihong.txgw.utils.UserLoginInfo;
import com.feihong.txgw.utils.greendao.GreenDaoOperateHelper;
import com.feihong.txgw.utils.manage.ThreadPoolManager;
import com.feihong.txgw.utils.sign.SignToken;
import com.just.agentweb.AgentWeb;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.feihong.txgw.ui.fragment.home.DiscoverFragment.INTENT_PRODUCTID;

/**
 * Created by Sabirjan on 2017/7/31.
 * TXGWApp.
 * 飞宏电子
 * 终端信息页面H5
 */

public class ProductInfoActivity extends BaseMVPCompateActivity<IProDetailContract.AbProDetailMainPrecenter> implements IProDetailContract.IProDetailMainView {

    public static final String INTENT_NAME = "productname";
    @BindView(R.id.iv_back)
    ImageButton ivBack;
    @BindView(R.id.txt_pageTitle)
    TextView txtPageTitle;
    @BindView(R.id.rl_contantframe)
    RelativeLayout webviewFrame;

    @BindView(R.id.product_detail_status_layout)
    View mStatusLayut;
    private AgentWeb mAgentWeb;
    private String productID = "";
    /**
     * 购物车数量统计
     */
    int cartAccount = 0;
    private int mMark;
    /**
     * 记录评论跳转
     */
    private static byte step = 1;

    private AgentWeb.PreAgentWeb mPreAgentWeb;
    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            if (activityIsDestory()) {
                return;
            }
            if (msg.what == 10) {
                loadPage();
            }
        }
    };

    private void loadPage() {
        if (mAgentWeb != null) {
            mAgentWeb.clearWebCache();
        }
        //GET 参数列表
        HashMap<String, String> params = new HashMap<>();
        params.put("sku_id", productID);
        params.put("latitude", UserLoginInfo.getUserCityInfo().getLatitude());
        params.put("longitude", UserLoginInfo.getUserCityInfo().getLongitude());
        params.put("city_code", UserLoginInfo.getUserCityInfo().getCityCode());
        String getparams = new SignToken().setSigen(params);

        String url = HttpTools.PRODUCT_INFO_WEBURL + "?" + getparams;
        LogUtils.i(TAG + ":商品详情路径：" + url);
        mAgentWeb = mPreAgentWeb.go(url);
        //水平不显示
        mAgentWeb.getWebCreator().getWebView().setHorizontalScrollBarEnabled(false);
        //垂直不显示
        mAgentWeb.getWebCreator().getWebView().setVerticalScrollBarEnabled(false);

        //屏蔽长按弹出复制按钮
        mAgentWeb.getWebCreator().getWebView().setOnLongClickListener(new View.OnLongClickListener() {

            @Override
            public boolean onLongClick(View v) {
                return true;
            }
        });
        serversJavaScript(cartOperation());
        if (mAgentWeb != null) {
            isAlRight = true;
            mAgentWeb.getWebLifeCycle().onResume();
        }
    }

    @Override
    public void setTheme() {
        productID = getIntent().getStringExtra(INTENT_PRODUCTID);
        mMark = getIntent().getIntExtra("shopCarRes", 0);

        if (TextUtils.isEmpty(productID)) {
            showSystemToast("产品ID不能为空！");
            finish();
        }

    }

    @Override
    public int setLayoutID() {
        return R.layout.activity_productinfo;
    }

    @Override
    public void onDestroy() {
        try {
            webviewFrame.removeAllViews();
            if (mAgentWeb != null) {
                mAgentWeb.getWebLifeCycle().onDestroy();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        if (mHandler != null && mHandler.getLooper() == Looper.getMainLooper()) {
            mHandler.removeCallbacksAndMessages(null);
        }
        super.onDestroy();
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        txtPageTitle.setText("商品详情");
        setSpecificTitleLayout(mStatusLayut);
    }

    private WebViewClient mWebViewClient = new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.contains("App/Comment/comment")) {
                txtPageTitle.setText("评论列表");
                step = 2;
            }
            return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            txtPageTitle.setText("评论列表");
            step = 2;
            return false;
            // return super.shouldOverrideUrlLoading(view, request);
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed();
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            webviewFrame.setVisibility(View.INVISIBLE);
            showDialog("网络问题", "因网络原因无法加载当前的页面数据，请关闭当前页面，重新进入看看！", new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    finish();
                }
            });
        }
    };

    @Override
    protected void onPause() {
        if (mAgentWeb != null) {
            mAgentWeb.getWebLifeCycle().onPause();
        }
        isAlRight = false;
        super.onPause();
    }

    private boolean isAlRight = false;

    @Override
    protected void onResume() {
        if (mAgentWeb != null) {
            if (!isAlRight) {
                mAgentWeb.getWebLifeCycle().onResume();
                refreshShopCarNum();
            }
        }
        super.onResume();
    }

    //WebChromeClient
    private WebChromeClient mWebChromeClient = new WebChromeClient() {


    };

    @Override
    public void bindData() {
        mPreAgentWeb = AgentWeb.with(this)
                .setAgentWebParent(webviewFrame, new RelativeLayout.LayoutParams(-1, -1))
                .useDefaultIndicator()
                .setWebChromeClient(mWebChromeClient)
                .setWebViewClient(mWebViewClient)
                .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)
                .setMainFrameErrorView(R.layout.agentweb_errorlayout, R.id.agentweb_re_query_data_layout)
                .createAgentWeb()
                .ready();
//       y
        ThreadPoolManager.getInstance().execute(new Runnable() {
            @Override
            public void run() {
                RefreshToken.getInstance().RetrofitRefreshTokenForGet();
                Message message = Message.obtain();
                message.what = 10;
                mHandler.sendMessage(message);
            }
        });
    }

    //购物车数量
    private int cartOperation() {
        List<ShopCarGoodsModel> list = GreenDaoOperateHelper.getAllGoods();
        if (list != null) {
            Iterator iterator = list.iterator();
            while (iterator.hasNext()) {
                ShopCarGoodsModel dbGoodsCartModel = (ShopCarGoodsModel) iterator.next();
                for (int i = 0; i < list.size(); i++) {
                    if (dbGoodsCartModel.getGoodsID() == list.get(i).getGoodsID() && !dbGoodsCartModel.getId().equals(list.get(i).getId())) {
                        LogUtils.i(TAG + ":剔除相同商品");
                        iterator.remove();
                        break;
                    }
                }
            }
        }

        int cartNum = 0;
        if (list != null) {
            for (ShopCarGoodsModel cartMode : list) {
                if (cartMode.getGoodsStatus() == 1) {
                    cartNum += cartMode.getGoodsNum();
                }
            }
            LogUtils.i(TAG + "未登录调用java,上传购物车数据:: " + cartNum);
            cartAccount = cartNum;

//            }
        }
        return cartAccount;
    }

    private void serversJavaScript(int count) {
        LogUtils.i(TAG + "购物车数量是 :  " + count);

        mAgentWeb.getJsInterfaceHolder().addJavaObject("android", new ProductInfoWebViewInterface(mAgentWeb, this, productID, count, new ActionCallBack() {
            @Override
            public void addcart(String addcartinfo) {
                LogUtils.i(TAG + ": 添加购物车:" + addcartinfo);
                addCart(addcartinfo);
            }

            @Override
            public void buy(String json) {
                LogUtils.i(TAG + ":购买商品:" + json);
                buyGoods(json);
            }

            @Override
            public void gotoCart() {
                if (mMark == 110) {
                    finish();
                } else {
                    Intent intent = new Intent();
                    intent.setClass(ProductInfoActivity.this, MyShopCartActivity.class);
                    startActivity(intent);
                }
            }
        }));
    }

    private void buyGoods(String json) {

        if (json == null || json.trim().length() == 0) {
            showSystemToast("数据错误！");
            return;
        }


        ShopCarGoodsModel model = null;
        try {
            model = new ShopCarGoodsModel();
            JSONObject obj = JSON.parseObject(json);
            int sku_id = obj.getIntValue("sku_id");
            int nums = obj.getIntValue("sku_num");
            String sku_name = obj.getString("sku_name");
            float shop_price = obj.getFloat("shop_price");
            String sub_title = obj.getString("subtitle");
            String thumb = obj.getString("thumb");
            int number = obj.getIntValue("number");
            String spec = obj.getString("spec");
            //产品总数量
            model.setGoodsAllNum(number);
            //产品名称
            model.setGoodsName(sku_name);
            //产品图片
            model.setGoodsPic(thumb);
            //数量
            model.setGoodsNum(nums);
            //附加标题
            model.setGoodsSubtitle(sub_title);
            //ID
            model.setGoodsID(sku_id);
            model.setIsUpdate(0);
            //产品价格
            model.setGoodsPrice(shop_price);
            model.setAddTime(System.currentTimeMillis());
            model.setGoodsSpec(spec);
            ArrayList<ShopCarGoodsModel> mOrderInfo = new ArrayList<>();
            mOrderInfo.add(model);
            Intent intent = new Intent(this, ToCreateOrderActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("orderInfo", JSON.toJSONString(mOrderInfo));
            intent.putExtras(bundle);
            intent.putExtra("type", 0);
            checkLoginAndStartIntent(intent);

        } catch (Exception ex) {
            ex.printStackTrace();
            LogUtils.i("操作失败！" + ex);
            showSystemToast("操作失败！" + ex);
            return;
        }
    }

    private void addCart(String json) {

        if (json == null || json.trim().length() == 0) {
            showSystemToast("数据错误！");
            return;
        }

        ShopCarGoodsModel model = null;
        try {
            model = new ShopCarGoodsModel();
            JSONObject obj = JSON.parseObject(json);
            int sku_id = obj.getIntValue("sku_id");
            int nums = obj.getIntValue("nums");
            String sku_name = obj.getString("sku_name");
            float shop_price = obj.getFloat("shop_price");
            String sub_title = obj.getString("sub_title");
            String thumb = obj.getString("thumb");
            int number = obj.getIntValue("number");
            String spec = obj.getString("spec");

            //未登录的用户数据保存本地数据库
            List<ShopCarGoodsModel> shopCarGoodsModels = GreenDaoOperateHelper.getModel(ShopCarGoodsModelDao.Properties.GoodsID, sku_id + "");
            ShopCarGoodsModel tempModel = (shopCarGoodsModels != null && shopCarGoodsModels.size() != 0) ? shopCarGoodsModels.get(0) : null;
            if (tempModel != null && tempModel.getGoodsNum() >= number) {
                showDialog(null, "此商品库存不足");
                return;
            }
            //产品总数量
            model.setGoodsAllNum(number);
            //产品名称
            model.setGoodsName(sku_name);
            //产品图片
            model.setGoodsPic(thumb);
            //数量
            model.setGoodsNum(nums);
            //附加标题
            model.setGoodsSubtitle(sub_title);
            //ID
            model.setGoodsID(sku_id);
            model.setIsUpdate(0);
            //产品价格
            model.setGoodsPrice(shop_price);
            model.setAddTime(System.currentTimeMillis());
            model.setGoodsSpec(spec);
            model.setAction("add");
            if (UserLoginInfo.isUserLogin()) {
                //已经登录的用户服务端同步
                addToServer(model);
            } else {
                if (tempModel != null) {
                    int localNum = 0;
                    model.setId(Long.valueOf(tempModel.getId()));
                    localNum = tempModel.getGoodsNum();
                    nums = nums + localNum;
                    //数量
                    model.setGoodsNum(nums);
                }
                GreenDaoOperateHelper.updateGoods(model);

                List<ShopCarGoodsModel> list = GreenDaoOperateHelper.getAllGoods();
                if (list != null) {
                    Iterator iterator = list.iterator();
                    while (iterator.hasNext()) {
                        ShopCarGoodsModel dbGoodsCartModel = (ShopCarGoodsModel) iterator.next();
                        for (int i = 0; i < list.size(); i++) {
                            if (dbGoodsCartModel.getGoodsID() == list.get(i).getGoodsID() && !dbGoodsCartModel.getId().equals(list.get(i).getId())) {
                                LogUtils.i(TAG + ":剔除相同商品");
                                iterator.remove();
                                break;
                            }
                        }
                    }
                }
                int count = 0;
                if (list != null) {
                    for (ShopCarGoodsModel cartMode : list) {
                        if (cartMode.getGoodsStatus() == 1) {
                            count += cartMode.getGoodsNum();
                        }
                    }
                }
                LogUtils.i(TAG + "------------未登录的用户数据保存本地数据库------------" + count);
                mAgentWeb.getJsAccessEntrace().quickCallJs("cartNum", "" + count);

                ToastUtils.showAddShopCarSuccessToast(ProductInfoActivity.this);
                EventBus.getDefault().post(new UpdateCartMessage());
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            showSystemToast("操作失败！");
            return;
        }
    }

    private void addToServer(ShopCarGoodsModel model) {
        ArrayList<ShopCarGoodsModel> list = new ArrayList<>();
        list.add(model);
        mPresenter.addGoodsToShopCar(list);
    }

    private void refreshShopCarNum() {
        mAgentWeb.getJsAccessEntrace().quickCallJs("cartNum", "" + cartOperation());
    }

    @Override
    public void onUserLogin(LoginMessage loginMessage) {

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (mAgentWeb.handleKeyEvent(keyCode, event)) {
            step = 1;
            txtPageTitle.setText("商品详情");
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void addGoodsToShopCarResult(GoodsCartParser goodsCartParser) {
        dismissProgressDialog();
        List<GoodsCartParser.DataBean> items = goodsCartParser.getData();
        if (goodsCartParser.getCode() == 200) {
            GreenDaoOperateHelper.updateDataBeanGoods(items);
            EventBus.getDefault().post(new UpdateCartMessage());

            int count = 0;
            //统计购物车一共有多少商品
            if (items.size() > 0) {
                for (GoodsCartParser.DataBean data : items) {
                    if ("1".equals(data.getStatus())) {
                        count += Integer.parseInt(data.getNums());
                    }
                }
            }

            LogUtils.i(TAG + "-----cart_num---------" + count);
            mAgentWeb.getJsAccessEntrace().quickCallJs("cartNum", "" + count);


            ToastUtils.showAddShopCarSuccessToast(ProductInfoActivity.this);
        } else {
            showSystemToast(goodsCartParser.getMsg());
        }
    }

    @Override
    public void loadDataComplated() {

    }

    @Override
    public void loadDataError() {
        dismissProgressDialog();
        showSystemToast(getString(R.string.connect_service_error));
    }

    @NonNull
    @Override
    public AbBasePrecenter initPresenter() {
        return ProDetailMainPrecenter.create();
    }

    public interface ActionCallBack {
        public void addcart(String addcartinfo);

        public void buy(String json);

        public void gotoCart();
    }

    @OnClick(R.id.iv_back)
    public void Onclick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                if (step == 1) {
                    finish();
                } else if (step == 2) {
                    step = 1;
                    txtPageTitle.setText("商品详情");
                    mAgentWeb.back();
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onBackPressedSupport() {
        super.onBackPressedSupport();
        if (step == 1) {
            finish();
        } else if (step == 2) {
            step = 1;
            txtPageTitle.setText("商品详情");
            mAgentWeb.back();
        }
    }
}
